package org.chunchu.todo.dao;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import org.chunchu.todo.LogUtils;
import org.chunchu.todo.model.Category;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.provider.BaseColumns;

public class CategoryDao {

	public static final String T_CATEGORY = "t_category";

	public static final String F_NAME = "name";
	public static final String[] ALL_COLUMNS = { BaseColumns._ID, F_NAME };

	@Inject
	DatabaseOpenHelper helper;

	public CategoryDao() {
	}

	public List<Category> findAll() {
		LogUtils.d("Category.findAll");
		SQLiteDatabase database = helper.getDatabase();
		Cursor cursor = database.query(T_CATEGORY, ALL_COLUMNS, null, null,
				null, null, null);
		List<Category> result = new ArrayList<Category>(cursor.getCount());
		LogUtils.i(cursor.getCount(), " categories found ");
		while (cursor.moveToNext()) {
			Category category = new Category(cursor.getLong(0),
					cursor.getString(1));
			result.add(category);
		}
		return result;
	}

	public void remove(long id) {
		LogUtils.d("Category.remove", id);
		SQLiteDatabase database = helper.getDatabase();
		database.delete(T_CATEGORY, BaseColumns._ID + " = ? ",
				new String[] { String.valueOf(id) });
	}

	public void add(String categoryName) {
		LogUtils.d("Category.add", categoryName);
		SQLiteDatabase database = helper.getDatabase();
		helper.addCategory(database, categoryName);
	}

	public boolean isValid(String name) {
		boolean value = name != null && name.trim().length() > 0;
		LogUtils.i("Category[", name, "].isValid", value);
		return value;
	}

	public void update(Category editCategory) {
		LogUtils.d("Updating category", editCategory.getId(), "new name",
				editCategory.getName());
		ContentValues values = new ContentValues();
		values.put(F_NAME, editCategory.getName());
		SQLiteDatabase database = helper.getDatabase();
		database.update(T_CATEGORY, values, BaseColumns._ID + " = ? ",
				new String[] { String.valueOf(editCategory.getId()) });
	}

	public Category findById(long id) {
		LogUtils.d("Category.findById", id);
		Category newCategory = null;
		SQLiteDatabase database = helper.getDatabase();
		Cursor cursor = database.query(T_CATEGORY, ALL_COLUMNS, BaseColumns._ID
				+ " = ? ", new String[] { String.valueOf(id) }, null, null,
				null);
		if (cursor.moveToFirst()) {
			newCategory = new Category(cursor.getLong(0), cursor.getString(1));
		}
		return newCategory;
	}

}
